﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Xml.Linq;
using Lync.Widget.Library.Configuration;
using Lync.Widget.Library.Presentation.Entities;

namespace Lync.Widget.Library.Presentation.Models
{
    public class FiltersModel : IFiltersModel
    {
        const string ConfigurationPath = @"\Configuration\Admapping.config";

        public XElement GetConfigurationXml()
        {
            var path = HttpContext.Current.Server.MapPath(ConfigurationPath);
            return File.Exists(path) ? XElement.Load(path) : null;
        }

        public void Remove()
        {
            var path = HttpContext.Current.Server.MapPath(ConfigurationPath);
            
            if (File.Exists(path))
            {
                File.Delete(path);
            }
        }

        public IList<IFilter> GetAll()
        {
            if (GetConfigurationXml() == null) return null;

            var configurationSection = ActiveDirectoryMappingConfiguration.Load();

            var filters = configurationSection.Mappings.Select(filter => new Filter
            {
                Id = filter.Id,
                Name = filter.Name,
                QuerystringParam = filter.QuerystringParam,
                Wildcard = filter.Wildcard,
                
            }).Cast<IFilter>().ToList();

            return filters;
        }

        public void Save(IList<IFilter> filters)
        {
            var root = new XElement("activedirectoryMappings");

            foreach (var filter in filters)
            {
                root.Add(new XElement("add",
                                                new XAttribute("id", filter.Id),
                                                new XAttribute("name", filter.Name),
                                                new XAttribute("querystringparam", filter.QuerystringParam),
                                                new XAttribute("wildcard", filter.Wildcard)));
            }

            root.Save(HttpContext.Current.Server.MapPath(ConfigurationPath));
        }        
    }
}